package com.test.exoplayertest.player;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.test.exoplayertest.player.interfaces.PlayerEventInterface;
import com.test.exoplayertest.player.manager.PlayerManager;
import com.test.exoplayertest.player.utils.PlayerUtil;

/**
 * @author wuxiaotao on 2017/6/15.
 */

public abstract class BaseVideoActivity extends AppCompatActivity implements PlayerEventInterface<ViewGroup> {

    private PlayerManager mManager;
    private ViewGroup mPlayerLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mManager = new PlayerManager(this);
    }

    @Override
    public void attach(ViewGroup root) {
        mPlayerLayout = root;
        mManager.attach(root);
    }

    @Override
    public void detach() {
        mManager.detach();
    }

    @Override
    public void startPlay(String url, String type) {
        mManager.startPlay(url, type);
    }

    @Override
    public void release() {
        mManager.release();
    }

    @Override
    public void resume() {
        mManager.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mManager.setSensorEnable(false);
        release();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mManager.setSensorEnable(true);
        resume();
    }

    public void beforeConfigurationChanged(boolean isLand){

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        boolean isLand =newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
        beforeConfigurationChanged(isLand);
        adJustPlayerLayout(isLand);
        mManager.onConfigurationChanged(newConfig);
    }

    public void adJustPlayerLayout(boolean isLand) {
        if (null != mPlayerLayout) {
            if (!isLand) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                int height = (int) (PlayerUtil.getDeviceWidth(this) / 16.0 * 9);
                mPlayerLayout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                mPlayerLayout.getLayoutParams().height = height;
            } else {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mPlayerLayout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                mPlayerLayout.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
            }
        }
    }
}
